<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="dialogFormVisible = !dialogFormVisible"
        >添加角色</el-button
      >
      <!-- 角色列表 -->
      <el-table :data="roleslist">
        <!-- 展开权限表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['top', index === 0 ? ['buttom'] : '']"
            >
              <!-- 第一列 一级权限 -->
              <el-col :span="5" justify="center" type="flex">
                <el-tag>{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二列 二级权限 -->
              <el-col :span="19">
                <!-- 第二列 -->
                <el-row
                  v-for="(i, index) in item.children"
                  :key="i.id"
                  :class="[index === 0 ? '' : 'buttom']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="5">
                    <el-tag type="success">{{ i.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-row>
                    <el-col v-for="i1 in i.children" :key="i1.id" :span="19">
                      <el-tag
                        type="warning"
                        closable
                        @close="handleClose(scope.row, i1.id)"
                        >{{ i1.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 序列表 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getid(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="distribution(scope.row)"
              >分配权限</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteuser(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色框 -->
      <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="form" status-icon :model="form">
          <!-- ref="ruleForm"获取数据，通过在el-form-item 添加属性prop="username"来定义规则 status-icon验证反馈加载图标 小圈圈-->
          <el-form-item label="角色名称" label-width="90px" prop="roleName">
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="90px">
            <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <!-- 此处回调函数必须加括号 adduser()-->
          <el-button type="primary" @click="adduser('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑角色框 -->
      <el-dialog title="编辑角色" :visible.sync="isFormVisible">
        <el-form :rules="rules" ref="form" status-icon :model="form">
          <!-- ref="ruleForm"获取数据，通过在el-form-item 添加属性prop="username"来定义规则 status-icon验证反馈加载图标 小圈圈 -->
          <el-form-item label="角色名称" label-width="90px" prop="roleName">
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="90px">
            <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isFormVisible = false">取 消</el-button>
          <!-- 此处回调函数必须加括号 edituser() -->
          <el-button type="primary" @click="edituser('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="jurisdictiondialogVisible"
        width="50%"
        @close='clearkeys'
      >
        <el-tree
          :data="jurisdiction"
          show-checkbox
          default-expand-all
          ref="tree"
          highlight-current
          :props="defaultProps"
          node-key="id"
          :default-checked-keys="keys"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="jurisdictiondialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="putallid(roleid)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkroleName = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          return callback(new Error("角色名称不能为空"));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      jurisdictiondialogVisible: false, //权限编辑框开关
      isFormVisible: false, //角色编辑框开关
      dialogFormVisible: false, //角色添加框开关
      roleslist: [],//角色列表
      jurisdiction:[],//单个角色的权限列表
      keys:[],//保存的权限id 
      roleid:'',
      defaultProps:{
        children: 'children',
        label:'authName'
      },
      // 编辑角色 和删除角色 form表单
      form: {
        id: 0,
        roleName: "",
        roleDesc: "",
      },
      //  form表单校验规则
      rules: { roleName: [{ validator: checkroleName, trigger: "blur" }] },
    };
  },
  created() {
    this.getroleslist();
  },
  methods: {
    //  获取角色列表
    async getroleslist() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status === 200) {
        this.roleslist = res.data;
        console.log(this.roleslist);
      } else {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: "error",
        });
      }
    },
    //  添加角色
    adduser(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("roles", this.form);
          // console.log(res);
          if (res.meta.status === 201) {
            this.dialogFormVisible = !this.dialogFormVisible;
            this.getroleslist();
            return this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //  编辑角色
    edituser(formName) {
      console.log("编辑");
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          console.log("编辑进入");
          const { data: res } = await this.$http.put(
            `roles/${this.form.id}`,
            this.form
          );
          console.log(res);
          if (res.meta.status === 200) {
            this.getroleslist();
            this.isFormVisible = !this.isFormVisible;
            return this.$message({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 触发规则方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //  删除角色
    async deleteuser(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status === 200) {
            this.getroleslist();
          }
          this.$message({
            type: "success",
            message: res.meta.msg,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //  获取id 存入form 表单对象
    getid(id) {
      this.isFormVisible = !this.isFormVisible;
      this.form.id = id;
    },
    //  删除角色指定权限
    handleClose(role, rightId) {
      let roleId = role.id;
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete(
            `roles/${roleId}/rights/${rightId}`
          );
          if (res.data.meta.status === 200) {
            // 这里可以对handleClose(role,rightId)中的role参数重新赋值，从而影响局部刷新，这是小技巧
            role.children = res.data.data;
          }
          this.$message({
            type: "success",
            message: res.data.meta.msg,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 打开权限编辑框
   async distribution(role) {
      this.roleid=role.id
      const {data:res} =await this.$http.get(`rights/tree`)
      if(res.meta.status===200){
        this.jurisdiction=res.data
        this.getjurisdictionID(role,this.keys)
        this.jurisdictiondialogVisible = !this.jurisdictiondialogVisible;
      } else{
        return console.log(res.meta.msg);
      }
      console.log(res);
    },
    //递归函数 把已选中的权限ID保存到keys数组中 node是节点 ， arr是数组
    getjurisdictionID(node,arr){
        if(!node.children){
           return  arr.push(node.id)
        }
        node.children.forEach(item =>this.getjurisdictionID(item,arr))
    },
    //关闭编辑权限框 清空keys数组
    clearkeys(){
      this.keys=[]
    },
    //提交选中权限ID
  async  putallid(roleid){
      const id=[
        //getCheckedKeys方法返回目前被选中的节点的 key 所组成的数组
        // ... 把数组拆分到 id数组中 
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      //使用数组方法join(',') 把数组转为以 ',' 连接的字符串
      const ids=id.join(',')
     const {data:res}=await this.$http.post(`roles/${roleid}/rights`,{rids:ids})
     
     if(res.meta.status===200){
       this.getroleslist()
    this.jurisdictiondialogVisible=!this.jurisdictiondialogVisible
       this.$message({
            type: "success",
            message: res.meta.msg,
          });
     }
    }
  },
};
</script>

<style scpoed>
.el-tag {
  margin: 10px 0;
}
.el-row {
  display: flex;
  align-items: center;
}
.buttom {
  border-top: 1px solid #ebeef5;
}
.top {
  border-bottom: 1px solid #ebeef5;
}
.el-col-19 {
  margin: 0 5px;
}
</style>